<script>
	import Icon from 'svelte-awesome';
  	import {angleLeft } from 'svelte-awesome/icons';
	const worker = new Worker('./work/search.js');
	const paragraphWorker = new Worker('./work/setSpan.js');
	try{
		window.$G.removeBackButton();
	}catch(e){}
	function getData(){
		return new Promise((resolve,reject)=>{
			var url = "./data.txt"
			var request = new XMLHttpRequest();
			request.open("get", url);
			request.send(null);
			request.onload = function () {
				if (request.status == 200) {
					resolve(request.responseText)
				}else{
					reject({msg:"加载失败"})
				}
			}
		})
	}
	let texts = [];
	let userSearchText = ""
	let userSearchResukt = []
	let selectIndex = -1;
	let plist = {}

	getData().then((data)=>{
		texts = data.split(/\n{4,}/);
		// console.log([...new Set(data.split(""))].join(""))
	})

	let timeout = null;
	function userSearch(){
		selectIndex = -1
		clearTimeout(timeout)
		timeout = setTimeout(() => {
			worker.postMessage({
				texts:texts,
				userSearchText:userSearchText
			});	
			worker.onmessage = function (e) {
				var data = e.data;
				userSearchResukt = data;
				plist = {}
				console.log(userSearchResukt.length,"userSearchResukt");
			}
		}, 500);
	}
	
	function setSpan(index,str,splitText){
		var promise={}
		promise.p=new Promise((resolve,reject)=>{
			promise.resolve=resolve;
			promise.reject=reject;
		})
		plist[index]=promise
		paragraphWorker.postMessage({
			str:str,
			splitText:splitText,
			index:index
		})
		paragraphWorker.onmessage = function(e){
			// plist[e.data.index].resolve(e.data)
			let index=e.data.index
			plist[index].data=e.data;
			if(index<10){
				plist[index].resolve(e.data)
			}
		}
		return plist[index].p
	}
	
	function open(index){
		if(selectIndex == index){
			selectIndex = -1
		}else{
			selectIndex = index
		}
		
		console.log(index,"0000");
	}
	function back(){
		try{
			window.$G.exitWebApp();
		}catch(e){

		}
	}
	function saveImage(container, options = {}){
		return new Promise((resolve,reject)=>{
			const scale = window.devicePixelRatio;
			const cwidth = container.offsetWidth;
			const cheight = container.offsetHeight;
			let { width, height } = options;
			width = width || cwidth;
			height = height || cheight;
			const ops = {scale,useCORS: true,allowTaint: false,...options};
			html2canvas(container,ops).then(canvas => {
				// canvas.toBlob((blob) => {
				// 	// console.log(blob,"000-0000")
				// 	resolve(blob);
				// }, 'image/webp', 0.1);
				let  base64=canvas.toDataURL("image/webp", 1)	
				resolve(base64);
				// resolve(URL.createObjectURL(blob));
			});
		})
	}
	function blobToDataURI(blob, callback) {
		var reader = new FileReader();
		reader.readAsDataURL(blob);
		reader.onload = function (e) {
			callback(e.target.result);
		}
	}
	//  function getSelectedText() {
	// 	return window.getSelection?window.getSelection():document.selection.createRange().text;
	//  }
	 function saveforImage(index){
		
		try{
			window.$G.setClipboard({
                data:userSearchResukt[index],
                success(){
					Toastify({
						text: "复制成功",
						duration: 3000,
						newWindow: true,
						close: false,
						gravity: "top", 
						position: "center",
						stopOnFocus: true,
						backgroundColor: "gray",
					}).showToast();
                },
                fail(err){
					Toastify({
						text: "复制成功",
						duration: 3000,
						newWindow: true,
						close: false,
						gravity: "top", 
						position: "center",
						stopOnFocus: true,
						backgroundColor: "red",
					}).showToast();
                },
            });
		}catch(e){}

		//  let dom = document.querySelector(`.index${index} pre`)
		//  let dom = document.querySelector(`.index${index} pre`)
		//  console.log(dom,"dom")
		//  dom.querySelectorAll(".searchWords").forEach((d)=>{
		// 	d.classList.add("noSelect");
		//  })
		// saveImage(dom).then((data)=>{
		// 	dom.querySelectorAll(".searchWords").forEach((d)=>{
		// 		d.classList.remove("noSelect");
		// 	})
		// 	let a = document.createElement('a')
		// 	a.download = 'ahQLuXunSpeech.webp'
		// 	console.log(data,"data")
		// 	a.href = data;
		// 	a.click()
		// })
		
	 }
	 window.onscroll=function(e){
		let container=document.querySelector(".text_container")
		var top = document.documentElement.scrollTop || document.body.scrollTop;//滚动条y轴上的距离
		// let endIndex = parseInt((top+window.innerHeight)/container.offsetHeight);
		if(container){
			let index = parseInt(top/container.offsetHeight);
			showCell(index,top);
		}
		
	 }
	 function showCell(index,top){
		//  根据大概的位置去获取真实的位置
		document.querySelectorAll(".text_container").forEach((item,index)=>{
			if(item.offsetTop>top&&item.offsetTop<top+window.innerHeight){
					// 应该正常显示的索引值
					plist[index].resolve(plist[index].data)
			}
		})
	 }
</script>

<main>
	<div>
		<div class="userSearch_container">
			<div class="back" on:click={back}>
				<Icon data={angleLeft} scale="2"/>
			</div>
			<input class="userSearch" type="text" on:input={userSearch} bind:value={userSearchText} placeholder="搜索鲁迅说过的关键字">
		</div>
		<div class="container">
			{#each userSearchResukt as text,index}
			<div class="text_container index{index} {selectIndex==index?'show':''}">
				<div class="saveForImage" on:click={()=>{saveforImage(index)}}>复制</div>
				<!-- <pre class="text">
					{@html setSpan(index,text,userSearchText)}
				</pre> -->
				<pre class="text">
					{#await setSpan(index,text,userSearchText)}
						<p>加载中</p>
					{:then info}
						{#if info&&info.result}
							{@html info.result}
						{/if}
					{:catch error}
						<p style="color: tomato;">{error}</p>
					{/await}
				</pre>
				
				<p class="open {selectIndex==index?'fixed':''}" on:click={()=>{open(index)}}>{selectIndex==index?"折叠":"展开"}</p>
			</div>
			{/each}
		</div>
	</div>
</main>

<style>
	main {
		text-align: center;
		padding: 1em;
		margin: 0 auto;
	}
	.back{
		font-size: 2rem;
		margin-right:1rem;
		width:4.5rem;
		height: 4.5rem;
		background: white;
		white-space: nowrap;
		border-radius: 0.5rem;
		display: flex;
		align-items: center;
		justify-content: center;
		box-shadow: 0px 0rem 1rem rgb(221, 221, 221);
		color: #1e1e1e;
	}
	.container{
		padding-top: 10rem;
		box-sizing: border-box;
	}
	.userSearch_container{
		position: fixed;
		width: 100%;
		height: 7rem;
		top: 0px;
		left: 0px;
		z-index: 2;
		display: flex;
		align-items: center;
		justify-content: center;
	}
	.userSearch{
		width: 70%;
		height: 4.5rem;
		font-size: 1.5rem;
		text-align: center;
		border-radius: 0.5rem;
		border: 2px solid rgb(231, 231, 231);
		box-shadow: 0px 0rem 1rem rgb(221, 221, 221);
	}
	.userSearch:focus{
		border: none;
	}
	.open{
		font-size: 2rem;
		text-align: right;
		font-weight: bold;
		padding: 2rem 0px;
		/* padding-bottom: constant(safe-area-inset-bottom);
		padding-bottom: env(safe-area-inset-bottom); */
		padding-right: 2rem;
		color: rgb(63, 63, 63);
		width: 100%;
		position: absolute;
		bottom: 0;
		background: #e9e9e9;
		box-sizing: border-box;
	}
	.open.fixed{
		position: fixed;
		right: 0;
		left: 0;
		bottom: 0;
		width: 100%;
		background: rgb(219, 219, 219);
		text-align: center;
		z-index: 2;
		
	}
	.text_container{
		width: 100%;
		max-width: 100%;
		padding: 1rem 0rem;
		padding-bottom: 0px;
		max-height: 30rem;
		box-sizing: border-box;
		overflow: hidden;
		border-bottom: 3px solid rgb(218, 218, 218);
		position: relative;
		display: flex;
		flex-flow: column;
		overflow-x: scroll;
	}
	.saveForImage{
		position: absolute;
		left: 3rem;
		top: 1rem;
		border: 1px solid #bbbbbb;
		padding: 0.5rem 1rem;
		box-sizing: border-box;
		color: #6c6c6c;
		border-radius: 0.5rem;
	}
	.text_container.show{
		max-height: inherit;
	}
	.text{
		width: 100%;
		/* max-width: 100%; */
		white-space:pre-wrap;
		text-align: left;
		text-align: justify;
		flex: 1;
		height: 100%;
		margin: 0px;
		padding: 0px 3rem;
		padding-bottom: 2rem;
		box-sizing: border-box;
		/* max-height: 1000px; */
		/* column-width: 200px;
		
		column-gap: 50px; */
	}


</style>